﻿using System;
using System.Collections.Generic;
using AccelerateSensor.Client.Forms;
using AccelerateSensor.Client.Tools;
using AccelerateSensor.Model.Node;
using AccelerateSensor.Service;
using ZbSkin.Tools;

namespace AccelerateSensor.Client.Controls
{
    public partial class NodeHistoryDataControl : PageControl
    {
        private readonly PagingControl _pagingControl;

        private string _gatewayUuid;
        private string _nodeUuid;
        private int _sleepTime;

        public NodeHistoryDataControl()
        {
            InitializeComponent();

            _pagingControl = new PagingControl();
            Controls.Add(_pagingControl);
        }

        private void NodeHistoryDataControl_Load(object sender, EventArgs e)
        {
            DataGridViewHelper.SetCommonStyle(dataGridView);
            DataGridViewHelper.SetDatetimeStyle(dataGridView, "ColumnUpdateTime");
            DataGridViewHelper.SetDatetimeStyle(dataGridView, "ColumnAddTime");
            dataGridView.ColumnHeadersVisible = true;
            ResizeControls();

            _pagingControl.ShowPage += OnShowPage;
        }

        private void NodeHistoryDataControl_Resize(object sender, EventArgs e)
        {
            ResizeControls();
        }

        private void ResizeControls()
        {
            SetRegion();

            dataGridView.Width = Width - 40;
            dataGridView.Height = Height - dataGridView.Top - 10 - _pagingControl.Height - btnDetail.Height * 2;

            _pagingControl.Width = dataGridView.Width;
            _pagingControl.Left = dataGridView.Left;
            _pagingControl.Top = dataGridView.Bottom + 10;

            btnDetail.Top = Height - (int) (btnDetail.Height * 1.5f);
            btnRefresh.Top = btnDetail.Top;
            btnNode.Top = btnDetail.Top;
        }

        #region ShowControl/HideControl

        protected override void ShowControl(object data)
        {
            base.ShowControl(data);

            var tuple = data as Tuple<string, string, int>;
            _gatewayUuid = tuple?.Item1;
            _nodeUuid = tuple?.Item2;
            _sleepTime = tuple?.Item3 ?? 0;
            label_title.Text = $@"节点历史数据 - {_nodeUuid}";

            UpdateDataGridView();
        }

        protected override void HideControl()
        {
            dataGridView.DataSource = null;
            GC.Collect();
            base.HideControl();
        }

        #endregion

        private void OnShowPage(int pageIndex)
        {
            GetPageNodeData(pageIndex);
        }

        private void UpdateDataGridView()
        {
            dataGridView.DataSource = null;

            if (string.IsNullOrWhiteSpace(_gatewayUuid) ||
                string.IsNullOrWhiteSpace(_nodeUuid))
            {
                return;
            }

            var nodeDataCountTask = AccelerateSensorService.Instance.GetNodeDataCountAsync(_nodeUuid);
            nodeDataCountTask.GetAwaiter().OnCompleted(() =>
            {
                //更新分页控件
                Context?.Post((state) =>
                {
                    _pagingControl.ResetControl(nodeDataCountTask.Result, Constants.CountPerPage);
                }, nodeDataCountTask.Result);

                //获取节点数据
                if (nodeDataCountTask.Result > 0)
                {
                    GetPageNodeData(1);
                }
            });
        }

        //获取页数据
        private void GetPageNodeData(int pageIndex)
        {
            var count = _pagingControl.GetPageCount(pageIndex);
            var nodeDataListTask = AccelerateSensorService.Instance.GetPageNodeDataAsync(
                _nodeUuid, Constants.CountPerPage, pageIndex, count);
            nodeDataListTask.GetAwaiter().OnCompleted(() =>
            {
                Context?.Post((state) =>
                {
                    var nodeDataList = state as List<NodeData>;
                    dataGridView.AutoGenerateColumns = false;
                    dataGridView.DataSource = nodeDataList;
                }, nodeDataListTask.Result);
            });
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            UpdateDataGridView();
        }

        private void btnNode_Click(object sender, EventArgs e)
        {
            InvokeSwitchPage(new Tuple<string, object>(Constants.PageTag.Gateway, _gatewayUuid));
        }

        private void btnDetail_Click(object sender, EventArgs e)
        {
            ShowData();
        }

        private void dataGridView_CellDoubleClick(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
        {
            ShowData();
        }

        private void ShowData()
        {
            var data = dataGridView.CurrentRow?.DataBoundItem as NodeData;
            if (data == null)
            {
                return;
            }

            var form = new FrmNodeHistoryData(_sleepTime, data);
            form.ShowDialog(ParentForm);
        }
    }
}
